import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  Breadcrumb,
  Button,
  Col,
  Container,
  Form,
  Modal,
  Row,
  InputGroup,
  FormControl
} from 'react-bootstrap';
import queryString from 'query-string';
import $ from 'jquery';

import { URL, CODE } from '../../config';
import {
  function_get_project,
  function_set_project_name,
  function_set_project_icon,
  function_set_project_notify
} from '../../actions/project';
import {
  function_getuserinfo,
  function_removeRoleByProject
} from '../../actions/member';
import AddMember from '../member/addMember';

class App extends Component {

  state = {
    pid: queryString.parse(this.props.location.search).pid,
    chatType: 1,
    show: false,
    showItem: null,
    projectNameErr: false,
    notifyUrlErr: false,
    isAjax: false,
    role: null
  }

  componentDidMount () {
    function_get_project(this.state.pid, this.props.dispatch, (admin, tester, developer, chatType) => {
      this.setState({chatType});
    })
  }

  setShow (item) {
    this.setState({
      show: true,
      showItem: item
    });
  }

  setHide () {
    this.setState({
      show: false,
      showItem: null
    });
  }

  showAddmemberBox (role) {
    this.setState({ role: role });
    this.setShow("addMember");
  }

  setProjectNotify () {
    let chatType = this.state.chatType;
    let notifyUrl = $(this.refs.notifyUrl).val();
    let reg = /(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-,@?^=%&:/~#]*[\w\-?^=%&/~#])?/;
    if (notifyUrl !== "" && !reg.test(notifyUrl)) {
      return this.setState({ notifyUrlErr: true });
    }
    let notifySecret = $(this.refs.notifySecret).val();
    if (notifyUrl !== "") {
      function_set_project_notify(chatType, notifyUrl, notifySecret, this.state.pid, this.props.dispatch, () => {
        this.setState({
          show: false,
          showItem: null,
          isAjax: false
        });
      });
    }
  }

  setProjectName () {
    let projectname = $(this.refs.projectName).val();
    if (projectname === "") {
      this.setState({ teanNameErr: true });
      return;
    } else {
      this.setState({ teanNameErr: false, isAjax: true });
      if (!this.state.isAjax) {
        function_set_project_name(projectname, this.state.pid, this.props.dispatch, () => {
          this.setState({
            show: false,
            showItem: null,
            isAjax: false
          });
        });
      }
    }
  }

  removeUser (role, uid, event) {
    event.persist();
    let nickname = "";
    let role2 = "";

    if (role === 3) {
      role2 = "开发人员"
      for (let index in this.props.projectList[this.state.pid].developer) {
        let item = this.props.projectList[this.state.pid].developer[index];
        if (item.uid === uid) {
          nickname = item.nickname;
          break;
        }
      }
    } else if (role === 4) {
      role2 = "测试人员"
      for (let index in this.props.projectList[this.state.pid].tester) {
        let item = this.props.projectList[this.state.pid].tester[index];
        if (item.uid === uid) {
          nickname = item.nickname;
          break;
        }
      }
    } else if (role === 2) {
      role2 = "上线人员"
      for (let index in this.props.projectList[this.state.pid].admin) {
        let item = this.props.projectList[this.state.pid].admin[index];
        if (item.uid === uid) {
          nickname = item.nickname;
          break;
        }
      }
    }

    let msg = "确定要将" + role2 + " " + nickname + " 从项目 " + this.props.projectList[this.state.pid].name + " 中移除？";
    let toRemoveUser = window.confirm(msg);
    if (toRemoveUser) {
      function_removeRoleByProject(uid, this.state.pid, role, result => {
        if (result.code === CODE.SUCCESS) {
          $(event.target).parent().fadeOut();
          if (uid === this.props.myuid) {
            function_getuserinfo(this.props.dispatch);
            this.props.history.push(URL.main_page);
            return;
          }
        }
      });
    }
  }

  handleFiles (event) {
    function_set_project_icon($(event.target)[0].files[0], this.state.pid, (path) => {
      $(this.refs.iconShow).attr("src", path);
    }, this.props.dispatch);
  }

  changeIcon () {
    document.getElementById("iconInput").click();
  }

  render () {
    return (
      <Container>
        <Breadcrumb>
          <Breadcrumb.Item href={URL.main_page}>项目列表</Breadcrumb.Item>
          <Breadcrumb.Item active>项目设置</Breadcrumb.Item>
        </Breadcrumb>
        <Row>
          <Col className="project-setting">
            <Row>
              <Col className="field">项目名称</Col>
              <Col className="content">
                {this.state.pid in this.props.projectList ?
                  this.props.projectList[this.state.pid].name : ""}
              </Col>
              {((Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || (this.props.roleList.indexOf(1) !== -1)) ?
                <Col className="operate" onClick={this.setShow.bind(this, "projectName")}>修改</Col>
                : null}
            </Row>
            <Row>
              <Col className="field">LOGO</Col>
              <Col className="content">
                <input type="file" accept="image/*" onChange={this.handleFiles.bind(this)} style={{ display: "none" }} id="iconInput" />
                {this.state.pid in this.props.projectList && this.props.projectList[this.state.pid].icon !== null ?
                  <img src={this.props.projectList[this.state.pid].icon} className="logo" alt="logo" /> :
                  <img src={require("./images/project_logo.png")} className="logo" alt="logo" />}
              </Col>
              {((Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || (this.props.roleList.indexOf(1) !== -1)) ?
                <Col className="operate" onClick={this.changeIcon.bind(this)}>更换</Col>
                : null}
            </Row>
            <Row>
              <Col className="field">消息通知</Col>
              <Col className="content">
                {this.state.pid in this.props.projectList && 'chatHookUrl' in this.props.projectList[this.state.pid] && this.props.projectList[this.state.pid].chatHookUrl !== "" ?
                  (this.props.projectList[this.state.pid].chatType === 1 ? "(钉钉)" : "(企业微信)") + ": " + this.props.projectList[this.state.pid].chatHookUrl.substr(0, 35) + "..." : "未设置"}
              </Col>
              {((Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || (this.props.roleList.indexOf(1) !== -1)) ?
                <Col className="operate" onClick={this.setShow.bind(this, "projectNotify")}>设置</Col>
                : null}
            </Row>
            <Row>
              <Col className="field">开发人员</Col>
              <Col className="content userlist">
                {this.state.pid in this.props.projectList && 'fatDeveloper' in this.props.projectList[this.state.pid] && this.props.projectList[this.state.pid].fatDeveloper.length > 0 ?
                  (this.props.projectList[this.state.pid].fatDeveloper.map(item => {
                    return (
                      <div className="item" key={item.uid}>
                        <span>{item.nickname}</span>
                        {(Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || this.props.myuid === item.uid ?
                          <i onClick={this.removeUser.bind(this, 3, item.uid)}>×</i>
                          : null}
                      </div>
                    )
                  }))
                  :
                  <p style={{ color: "gray" }}>该项目还没有开发人员，点击添加一个吧</p>}
              </Col>
              {((Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || (this.props.roleList.indexOf(1) !== -1)) ?
                <Col className="operate" onClick={this.showAddmemberBox.bind(this, "developer")}>添加</Col>
                : null}
            </Row>
            <Row>
              <Col className="field">测试人员</Col>
              <Col className="content userlist">
                {this.state.pid in this.props.projectList && 'fatTester' in this.props.projectList[this.state.pid] && this.props.projectList[this.state.pid].fatTester.length > 0 ?
                  (this.props.projectList[this.state.pid].fatTester.map(item => {
                    return (
                      <div className="item" key={item.uid}>
                        <span>{item.nickname}</span>
                        {(Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || this.props.myuid === item.uid ?
                          <i onClick={this.removeUser.bind(this, 4, item.uid)}>×</i>
                          : null}
                      </div>
                    )
                  }))
                  :
                  <p style={{ color: "gray" }}>该项目还没有测试人员，点击添加一个吧</p>}
              </Col>
              {((Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || (this.props.roleList.indexOf(1) !== -1)) ?
                <Col className="operate" onClick={this.showAddmemberBox.bind(this, "tester")}>添加</Col>
                : null}
            </Row>
            <Row>
              <Col className="field">上线人员</Col>
              <Col className="content userlist">
                {this.state.pid in this.props.projectList && 'fatAdmin' in this.props.projectList[this.state.pid] && this.props.projectList[this.state.pid].fatAdmin.length > 0 ?
                  (this.props.projectList[this.state.pid].fatAdmin.map(item => {
                    return (
                      <div className="item" key={item.uid}>
                        <span>{item.nickname}</span>
                        {(Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || this.props.myuid === item.uid ?
                          <i onClick={this.removeUser.bind(this, 2, item.uid)}>×</i>
                          : null}
                      </div>
                    )
                  }))
                  :
                  <p style={{ color: "gray" }}>该项目还没有上线人员，点击添加一个吧</p>}
              </Col>
              {((Object.keys(this.props.projectList).length>0 && this.props.projectList[this.state.pid].admin.indexOf(this.props.myuid)>-1) || (this.props.roleList.indexOf(1) !== -1)) ?
                <Col className="operate" onClick={this.showAddmemberBox.bind(this, "admin")}>添加</Col>
                : null}
            </Row>
          </Col>
          <Col className="project-setting-prop" sm={5}>
            <h4>消息通知</h4>
            <p>您需要在钉钉/企业微信上将项目有关开发、测试、上线人员拉到一个群中，相关事项，包括：提交测试请求、部署测试、预发布环境测试、代码上线等，将以消息通知的方式在群里发布</p>
            <h4>各个角色的权限职责</h4>
            <ul>
              <li>
                开发人员
                <p>负责项目各个微服务代码的开发工作，然后提交上线申请，拥有在测试环境刷新部署好的代码的权限</p>
              </li>
              <li>
                测试人员
                <p>可以在测试环境部署开发人员提交上线申请的代码，进行测试，测试通过后，流程流转到上线人员</p>
              </li>
              <li>
                上线人员
                <p>可以将测试通过的代码部署到预发布环境，让测试人员测试。最后点击上线按钮，完成merge request的上线部署</p>
              </li>
            </ul>
            <h4>注意事项：</h4>
            <p>上线人员同时拥有项目的管理权限，可以创建微服务、删除微服务、修改项目信息、配置项目相关人员等</p>
          </Col>
        </Row>
        <Modal className="projectName" show={this.state.show && this.state.showItem === "projectName"} onHide={this.setHide.bind(this)}>
          <Modal.Header>
            <Modal.Title>修改项目名称</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Form>
              <Form.Group>
                <Form.Control className={this.state.teanNameErr ? "error" : null} ref="projectName" defaultValue={this.state.pid in this.props.projectList ?
                  this.props.projectList[this.state.pid].name : ""} />
                {this.state.projectNameErr ?
                  <Form.Text className="text-muted">
                    项目名称不能为空
                </Form.Text>
                  : null}
              </Form.Group>
            </Form>
          </Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={this.setHide.bind(this)}>
              取消
            </Button>
            <Button variant="primary" onClick={this.setProjectName.bind(this)}>
              确定
            </Button>
          </Modal.Footer>
        </Modal>
        <Modal className="projectNotify" show={this.state.show && this.state.showItem === "projectNotify"} onHide={this.setHide.bind(this)}>
          <Modal.Header>
            <Modal.Title>消息通知设置</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Form>
              <Form.Group>
                <Form.Row>
                  <Col sm="3">
                    <Form.Control as="select" onChange={event => this.setState({chatType: parseInt(event.target.value)})} value={this.state.chatType}>
                      <option value="1">钉钉</option>
                      <option value="2">企业微信</option>
                    </Form.Control>
                  </Col>
                  <Col>
                    <InputGroup>
                      <FormControl
                      type="url"
                      ref="notifyUrl"
                      className={this.state.urlError ? "error" : ""}
                      placeholder="WebHook链接地址 http://"
                      defaultValue={this.state.pid in this.props.projectList ? this.props.projectList[this.state.pid].chatHookUrl : ""} />
                      {this.state.chatType === 1 ?
                        <FormControl ref="notifySecret" placeholder="WebHook密钥" />
                      : null}
                    </InputGroup>
                  </Col>
                </Form.Row>
                {this.state.notifyUrlErr ?
                  <Form.Text className="text-muted">
                    通知hook地址错误
                  </Form.Text>
                  : null}
              </Form.Group>
            </Form>
          </Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={this.setHide.bind(this)}>
              取消
            </Button>
            <Button variant="primary" onClick={this.setProjectNotify.bind(this)}>
              确定
            </Button>
          </Modal.Footer>
        </Modal>
        <AddMember
          show={this.state.show && this.state.showItem === "addMember"}
          onHide={this.setHide.bind(this)}
          role={this.state.role}
          pid={this.state.pid}
          onSubmit={(result) => {
            if (result.code === CODE.SUCCESS) {
              this.setHide();
              function_get_project(this.state.pid, this.props.dispatch, () => { })
            }
          }} />
      </Container>
    )
  }
}

function mapStateToProps (state) {
  return {
    projectList: state.project,
    roleList: state.account.roleList,
    myuid: state.account.uid,
  }
}

export default connect(mapStateToProps)(App);